from rest_framework import serializers
from apps.users.models import User


class UserListAPIViewSerialzer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email']


class UserCreateAPIViewSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['username', 'password', 'mobile', 'email']

    # 因为序列化器中对密码没有进行掩码操作，所有要重写create方法，调用Django中的方法
    def create(self, validated_data):
        try:
            user = User.objects.create_user(**validated_data)
        except User.DoesNotExist:
            return None
        return User

    # 针对个别的字段进行约束限制
    extra_kwargs = {
        'username': {
            'max_length': 20,
            'min_length': 5
        },
        'password': {
            'max_length': 20,
            'min_length': 8,
            'write_only': True

        },
    }
